// ignore_for_file: avoid_print

import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/native_dart_package.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/pages/mine/message_center/advertise_message/advertise_message_model.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/messsage/message_services.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/enums.dart';

class AdvertiseMessageController extends GetxController {
  final AdvertiseMessageState state = AdvertiseMessageState();
  List<AdvertiseMessageState> messagesList = [];
  final MessageServices messageServices = Get.put(MessageServices());
  RefreshController refreshController = RefreshController(
    initialRefresh: false,
  );
  int current = 1;
  int pageSize = 10;
  List<int> noticeIds = [];

  @override
  void onInit() {
    super.onInit();
    loadList();
  }

  /// 获取所有未读消息
  void collectUnreadAdvertise() {
    noticeIds.clear();
    for (var i = 0; i < messagesList.length; i++) {
      if (messagesList[i].status == AdvertiseStatusType.normal.value) {
        noticeIds.add(messagesList[i].noticeId!);
      }
    }
  }

  /// 请求列表数据
  Future<void> loadList() async {
      var params = {"current": current, "pageSize": pageSize,'noticeType':2};
        var result = await messageServices.getAnnouncementList(params);
      refreshController.loadComplete();
      refreshController.refreshCompleted();
      if (result != null) {
        var list = result['list'] ?? [];
        List<AdvertiseMessageState> tempList = [];
        list.forEach((item) => tempList.add(AdvertiseMessageState.fromJson(item)));
        if (current == 1) {
          messagesList.clear();
        }
        messagesList.addAll(tempList);
        if (result['total'] != null && result['total'] <= messagesList.length) {
          refreshController.loadNoData();
        }
        collectUnreadAdvertise();
        update();
      }
  }

  void onRefresh() {
    current = 1;
    loadList();
  }

  void onLoad() {
    current++;
    loadList();
  }

  /// 下拉刷新结束
  void endRefresh(List<AdvertiseMessageState>? list) {
    if (refreshController.isRefresh) {
      refreshController.refreshCompleted();
      if ((list?.length ?? 0) >= current) {
        refreshController.resetNoData();
      }
    } else {
      if (list == null) {
        refreshController.loadFailed();
      } else if ((list.isEmpty) || ((list.length) < current)) {
        refreshController.loadNoData();
      } else {
        refreshController.loadComplete();
      }
    }
  }

  /// 前往公告详情
  void goMessageDetail(int index) {
    Get.toNamed(RouterPath.advertiseMessageDetail, arguments: {
      'noticeId': messagesList[index].noticeId!,
    });
  }

  /// 全部已读确认弹框
  void showCupertinoAlertDialog(context) {
    BrnDialogManager.showConfirmDialog(
      context,
      message: ResKey.isAllRead.tr,
      cancel: ResKey.cancel.tr,
      confirm: ResKey.confirm.tr,
      themeData: BrnDialogConfig(
        contentTextStyle: BrnTextStyle(
          color: Colour.mainTextColor,
          fontWeight: FontWeight.w500,
          fontSize: 18.sp,
        ),
      ),
      onConfirm: () {
        updateAnnouncementStatus(noticeIds);
        Get.back();
      },
      onCancel: () => Get.back(),
    );
  }

  void updateAnnouncementStatus(noticeIds) async {
    Log.d('noticeIds==' + noticeIds.toString());
    if (noticeIds.length == 0) return;
    var params = {'noticeIds': noticeIds};
    await messageServices.updateAnnouncementStatus(params, onError: (err) {
      handleException(err);
      return false;
    });
    current = 1;
    loadList();
  }
}
